package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExsitException;
import com.atguigu.gulimall.member.exception.UsernameExsitException;
import com.atguigu.gulimall.member.service.MemberService;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    //会员等级
    @Autowired
    private MemberLevelDao memberLevelDao;

    @Autowired
    MemberDao memberDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询默认等级
     *
     * @param vo
     */
    @Override
    public void regist(MemberRegistVo vo) {
//        MemberDao memberDao = this.baseMapper;
        MemberEntity registVo = new MemberEntity();
        //设置默认等级
        MemberLevelEntity memberLevel = memberLevelDao.getDefaultLevel();
        registVo.setLevelId(memberLevel.getId());
        //检擦手机号和用户名是否唯一
        checkPhoneUnique(vo.getPhone()); //检擦电话号是否唯一
        checkUsernameUnique(vo.getUserName()); //检擦用户名是否唯一

        registVo.setMobile(vo.getPhone());//设置电话
        registVo.setUsername(vo.getUserName());//设置用户名
        registVo.setNickname(vo.getUserName());
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        registVo.setPassword(encode); //设置密码
        memberDao.insert(registVo);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExsitException {
        MemberDao memberdao = this.baseMapper;
        /**
         *  1、根据手机号查询 MemberEntity 表
         *  2、大于0 代表有数据、就抛出异常
         */
        Integer mobile = memberdao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneExsitException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExsitException {
        MemberDao memberdao = this.baseMapper;
        /**
         *  1、根据手机号查询 MemberEntity 表
         *  2、大于0 代表有数据、就抛出异常
         */
        Integer count = memberdao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameExsitException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        //查询用户名和手机号
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct)
                .or().eq("mobile", loginacct));

        if (memberEntity == null) {
            return null;
        } else {
            String passwordDb = memberEntity.getPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            /**
             * 第一个参数明文密码
             * 第二个参数数据库存的密文密码
             */
            boolean matches = encoder.matches(password, passwordDb);
            if (matches) {
                return memberEntity;
            } else {
                return null;
            }
        }

    }

    @Override
    public MemberEntity login(SocialUser user) throws Exception {
        //登陆注册合并逻辑
        String uid = user.getUid();
        //判断当前账户是否登陆过系统
        MemberDao baseMapper = this.baseMapper;
        MemberEntity selectOne = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        //如果根据微博的id查到的数量大于零、就是注册过
        if (selectOne != null) {
            MemberEntity memberEntity = new MemberEntity();
            memberEntity.setId(selectOne.getId());
            memberEntity.setAccessToken(user.getAccess_token());
            memberEntity.setExpiresIn(user.getExpires_in());
            //修改
            baseMapper.updateById(memberEntity);

            selectOne.setAccessToken(user.getAccess_token());
            selectOne.setExpiresIn(user.getExpires_in());
            System.out.println("MemberEntity{}"+ selectOne);
            return selectOne;
        } else {
            //2、没有查到当前社交用户对应的记录我们就需要注册一个
            MemberEntity regist = new MemberEntity();
            //3、查询当前社交用户的社交账户信息（昵称、性别等）
            HashMap<String, String> map = new HashMap<>();
            map.put("access_token", user.getAccess_token());
            map.put("uid", user.getUid());

            HttpResponse httpResponse = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), map);

            try {
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    //查询成功
                    String s = EntityUtils.toString(httpResponse.getEntity());
                    JSONObject jsonObject = JSON.parseObject(s);

                    //昵称
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");

                    //执行新增
                    regist.setNickname(name);
                    regist.setGender("m".equals(gender) ? 1 : 0);
                }
            } catch (Exception e) {
            }

            regist.setSocialUid(user.getUid());
            regist.setAccessToken(user.getAccess_token());
            regist.setExpiresIn(user.getExpires_in());
            memberDao.insert(regist);
            return regist;

        }
    }

}
